import 'dart:ui';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/services.dart';
import 'package:flutter_native_image/flutter_native_image.dart';
import 'package:magic_car/UI/Loading.dart';
import 'package:magic_car/UI/mykeyboard.dart' as board;
import 'package:magic_car/baoxiu/brandselect.dart';
import 'package:magic_car/baoxiu/cartype.dart';
import 'package:magic_car/jiance/papularInspects.dart';
import 'package:magic_car/jiance/start.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:toast/toast.dart';
import 'package:flutter/material.dart';
import 'package:magic_car/util/HttpHelper.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';
import 'package:date_format/date_format.dart';

class BusinessEditcarPage extends StatefulWidget {
  

  final String oid;

BusinessEditcarPage(this.oid);
  @override
  _MyHomePageState createState() => new _MyHomePageState(this.oid);
}

class _MyHomePageState extends State<BusinessEditcarPage> {
  String pwdData = '输入车牌';
  final String oid;
  _MyHomePageState(this.oid);
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  // VoidCallback：没有参数并且不返回数据的回调
  VoidCallback _showBottomSheetCallback;

  // TextEditingController _nametroller = new TextEditingController();
  // TextEditingController _agetroller = new TextEditingController();
  // TextEditingController _mobiletroller = new TextEditingController();
  // TextEditingController _validtroller = new TextEditingController();
  // TextEditingController _idcardtroller = new TextEditingController();
  // TextEditingController _expricetroller = new TextEditingController();
  // TextEditingController _passtroller = new TextEditingController();
  // TextEditingController _confirmpasstroller = new TextEditingController();
  List formList;
  bool agreen = false;
  File _image;
  String card_z = '';
  String card_f = '';
  bool select_img = false;
  String status = "";
  List imgs = new List();
  List img_url = new List();
  TextEditingController car_num = new TextEditingController();
    TextEditingController car_price = new TextEditingController();
    TextEditingController num_km = new TextEditingController();
    TextEditingController people = new TextEditingController();
    TextEditingController mobile = new TextEditingController();
    TextEditingController address = new TextEditingController();
    TextEditingController desrible = new TextEditingController();
  initState() {
    super.initState();
    _showBottomSheetCallback = _showBottomSheet;
    formList = [
      {
        "title": '车牌号',
        'sub_title': '云A00001',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': 6,
        'bottom': 1.0,
        'value': '',
        'code': '',
        'ctroller':car_num,
        'text_type':1,
        'max_length':0
      },
      // {
      //   "title": '上牌日期',
      //   'sub_title': '云A00001',
      //   'sub_color': Color.fromRGBO(27, 182, 251, 1),
      //   'type': 2,
      //   'bottom': 1.0,
      //   'value': '请选择日期',
      //   'code': ''
      // },
      {
        "title": '品牌',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': 3,
        'bottom': 1.0,
        'value': '请选择品牌',
        'code': '',
        'brand_id': '',
      },
      {
        "title": '车型',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': 3,
        'bottom': 10.0,
        'value': '请选择车型',
        'code': '',
        'type_id': ''
      },
       
      {
        "title": '车价（万）',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': 1,
        'bottom': 10.0,
        'value': '',
        'code': 'price',
        'ctroller':car_price,
        'text_type':1,
         'max_length':0
      },
      {
        "title": '联系人',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': 1,
        'bottom': 1.0,
        'value': '',
        'code': 'contact_people',
        'ctroller':people,
        'text_type':2,
        'max_length':5
      },
      {
        "title": '联系电话',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': 1,
        'bottom': 1.0,
        'value': '',
        'code': 'contact_mobile',
        'ctroller':mobile,
        'text_type':1,
        'max_length':11
      },
      // {
      //   "title": '地址',
      //   'sub_title': '云A00001云A00001云A00',
      //   'sub_color': Color.fromRGBO(27, 182, 251, 1),
      //   'type': 1,
      //   'bottom': 10.0,
      //   'value': '',
      //   'code': 'address',
      //   'ctroller':address,
      //   'text_type':2
      // },
      // {
      //   "title": '车型',
      //   'sub_title': '云A00001云A00001云A00',
      //   'sub_color': Color.fromRGBO(27, 182, 251, 1),
      //   'type': 3,
      //   'bottom': 10.0,
      //   'value': '',
      //   'code': ''
      // },
      {
        "title": '车源图片(至少上传一张)',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': 4,
        'bottom': 10.0,
        'value': '',
        'code': ''
      },
      {
        "title": '车源简介',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': 5,
        'bottom': 10.0,
        'value': '',
        'code': 'car_descrble',
        'ctroller':desrible
      },
    ];
    //imgs.add({'url':'''order["status"].toString() != "3"'''}'resource/images/user/upimg.png');
    imgs=[
      {
      'url':'',
      'name':'前脸',
      'isupdate':0
    },
    {
      'url':'',
      'name':'左前45度',
      'isupdate':0
    },
    {
      'url':'',
      'name':'右后45度',
      'isupdate':0
    },
    {
      'url':'',
      'name':'侧面',
      'isupdate':0
    },
    {
      'url':'',
      'name':'前排',
      'isupdate':0
    },
    {
      'url':'',
      'name':'后排',
      'isupdate':0
    },
    {
      'url':'',
      'name':'仪表台',
      'isupdate':0
    },
    {
      'url':'',
      'name':'主驾驶',
      'isupdate':0
    },
    {
      'url':'',
      'name':'发动机舱',
      'isupdate':0
    },
    {
      'url':'',
      'name':'车尾',
      'isupdate':0
    },
    {
      'url':'',
      'name':'底盘',
      'isupdate':0
    },
    {
      'url':'',
      'name':'亮点配置',
      'isupdate':0
    },
    
    ];
    loaduserinfo();
    loaddata();
  }
  void _showBottomSheet() {
    print('键盘出现');
    if(pwdData=="输入车牌"){
      setState(() {

      });
    }
    // new NumberKeyboardActionSheet(name: "1111", controller: car_num);
    setState(() {
      // disable the button  // 禁用按钮
      _showBottomSheetCallback = null;

    });

    /*
      currentState：获取具有此全局键的树中的控件状态
      showBottomSheet：显示持久性的质感设计底部面板
      解释：联系上文，_scaffoldKey是Scaffold框架状态的唯一键，因此代码大意为，
           在Scaffold框架中显示持久性的质感设计底部面板
     */
    _scaffoldKey.currentState
        .showBottomSheet<void>((BuildContext context) {
      /// 将自定义的密码键盘作为其child   这里将回调函数传入
      return new board. MyKeyboard(_onKeyDown,pwdData);
    })
        .closed
        .whenComplete(() {
      if (mounted) {
        setState(() {
          // re-enable the button  // 重新启用按钮
          _showBottomSheetCallback = _showBottomSheet;
        });
      }
    });
  }
  /// 密码键盘的整体回调，根据不同的按钮事件来进行相应的逻辑实现
  void _onKeyDown(board. KeyEvent data) {
  print("删除前车牌："+pwdData);
// 如果点击了删除按钮，则将密码进行修改
    if (data.isDelete()) {
      
      if(pwdData!="输入车牌"){
              if (pwdData.length > 0) {
        pwdData = pwdData.substring(0, pwdData.length - 1);
        setState(() {});
      }
      }
      if(pwdData.length==0){
       setState(() {
         pwdData="输入车牌";
       });
      }
    }
// 点击了确定按钮时
    else if (data.isCommit()) {
      print("点击完成");
      setState(() {
        pwdData=pwdData;
      });
      Navigator.of(context).pop();
//      if (pwdData.length != 7) {
////        Fluttertoast.showToast(msg: "密码不足6位，请重试", gravity: ToastGravity.CENTER);
//        return;
//      }
      // onAffirmButton();
    }
//点击了数字按钮时  将密码进行完整的拼接
    else {
      if(pwdData.length==0){

      }
      if(pwdData=="输入车牌"){
        setState(() {
          pwdData="";
        });
      }
      if (pwdData.length < 8) {
        pwdData += data.key;
      }
      setState(() {
        pwdData=pwdData;
      });
    }
  }

  loaduserinfo() async {
    // LoadingPage loadpage = new LoadingPage(context);
    // loadpage.show();
    SharedPreferences pref = await SharedPreferences.getInstance();
    Map<String, String> map = new Map();
    map["id"] = pref.getString('uid');

    HttpHelper.post(HttpHelper.API_BusinessInfo, (data) async {
      //loadpage.close();
      if (data != null) {
        print(data);
        //Toast.show(data["msg"], context);

        if (data["code"].toString() == "1") {
          if (data["info"]["avatar"].length != 0) {
            setState(() {
              // avatar = data["info"]["avatar"];
            });
          }
          var info = data["info"];
          setState(() {
            status = info["status"].toString();
          });
        }
      }
    }, params: map);
  }

  Widget layout() {
    List<Widget> tiles = [];
    Widget content;
    tiles.add(Align(
      alignment: Alignment.centerLeft,
        child: Padding(
            padding: new EdgeInsets.fromLTRB(10, 0, 0, 10),
            child: Text('填写基本信息'))));
    for (var item in formList) {
      var type = item["type"];
      if (type == 1) {
        //输入框
        tiles.add(inputWidget(item));
      } else if (type == 2) {
        //时间选择
        tiles.add(dateSelect(item));
      } else if (type == 3) {
        //类型选择
        tiles.add(cartype(item));
      } else if (type == 4) {
        //图片
        tiles.add(imagUp(item));
      } else if (type == 5) {
        tiles.add(textarea(item));
      }else if(type==6){
       tiles.add(carNuminput(item));
      }
    }
    // var btn = new SizedBox(
    //     width: double.infinity,
    //     height: 50,
    //     child: new FlatButton(
    //       child: Text('立即申请入驻'),
    //       textColor: Colors.white,
    //       color: Colors.white,
    //       //color: Color.fromRGBO(27, 182, 251, 1),
    //       onPressed: () {
    //         regist();
    //       },
    //     ));
    var btn = new Container(
        color: Color.fromRGBO(239, 239, 239, 1),
        //color:Colors.white,
        child: new Padding(
            padding: new EdgeInsets.fromLTRB(10, 0, 20, 0),
            child: new Material(
              color: Color.fromRGBO(239, 239, 239, 1),
              //INK可以实现装饰容器
              child: new Ink(
                //用ink圆角矩形
                //color: Color.fromRGBO(239, 239, 239, 1),
                decoration: new BoxDecoration(
                  //背景

                  color: Color.fromRGBO(255, 204, 48, 1),
                  //设置四周圆角 角度
                  borderRadius: BorderRadius.all(Radius.circular(18.0)),
                  //设置四周边框
                  border: new Border.all(
                      width: 1, color: Color.fromRGBO(255, 204, 48, 1)),
                ),
                child: new InkWell(

                    //圆角设置,给水波纹也设置同样的圆角
                    //如果这里不设置就会出现矩形的水波纹效果
                    borderRadius: new BorderRadius.circular(15.0),
                    //设置点击事件回调
                    onTap: () {
                      submit();
                    },
                    child: Container(
                      //设置 child 居中
                      alignment: Alignment(0, 0),
                      height: 36,
                      //color: Color.fromRGBO(239, 239, 239, 1),
                      width: double.infinity,
                      child: Text(
                        "保存",
                        style: TextStyle(color: Colors.white),
                      ),
                    )),
              ),
            )));
    tiles.add(btn);
    content = new Padding(
        padding: new EdgeInsets.fromLTRB(0, 0, 0, 10),
        child: new Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: tiles //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
            //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
            ));
    return content;
  }
  //车牌键盘布局
  
  Widget carNuminput(item) {
    DateTime initialDate = DateTime.now();
    Widget content = Padding(
        padding: new EdgeInsets.fromLTRB(0, 0, 0, item["bottom"]),
        child: Container(
          color: Colors.white,
          
          height: 50,
          child: 
          new GestureDetector(
            behavior: HitTestBehavior.opaque,
                      onTap: (){
                        FocusScope.of(context).requestFocus(FocusNode());
                        _showBottomSheetCallback();
                      },child:
          new Row(
            children: <Widget>[
              Expanded(
                child: new Padding(
                  padding: new EdgeInsets.fromLTRB(10, 0, 10, 0),
                  child: RichText(
                    text: TextSpan(
                        text: item["title"],
                        style: TextStyle(
                            fontSize: 15,
                            color: Color.fromRGBO(102, 102, 102, 1)),
                        children: [
                          // TextSpan(
                          //     text: '*',
                          //     style: TextStyle(fontSize: 14, color: Colors.red))
                        ]),
                  ),
                ),
                flex: 1,
              ),
              Expanded(
                child: 
                
                Padding(
                    padding: new EdgeInsets.fromLTRB(10, 0, 30, 0),
                    child: 
                    // new GestureDetector(
                    //   onTap: (){
                    //     _showBottomSheetCallback();
                    //   },
                    //   child:
                    Align(
                        alignment: Alignment.centerRight,
                        child: 
                        // new GestureDetector(
                        //     child: 
                            new Text(pwdData),
                            )),
                flex: 2,
              )
            ],
          ),
        )));
    return content;
  }
//加载数据
  loaddata() async {
    Map<String, String> map = new Map();
    map['oid'] = this.oid;
    //  SharedPreferences pref = await SharedPreferences.getInstance();
    //  map["id"]=pref.getString('uid');
    //  map["type"]="0";

    HttpHelper.post(HttpHelper.API_BussinessOrderDetail, (data) async {
      if (data != null) {
        if (data["code"].toString() == "1") {
          List oldlist = formList;
          var orderinfo = data["info"];
          for (var i = 0; i < oldlist.length; i++) {
            var item = oldlist[i];
            var str = "";
            if (i == 0){
              str = orderinfo["car_num"];
            }
            else if (i == 1){
              str = orderinfo["brand_string"]['name'];
              item['brand_id']=orderinfo["brand_string"]['id'];
            }
            else if (i == 2){
              str = orderinfo["cartype_string"]['name'];
              item['type_id']=orderinfo["cartype_string"]['id'];
            }
            else if (i == 3){
              str = orderinfo["car_price"];
            }
            else if (i == 4)
            {
              str = orderinfo["contact_people"];
            }else if(i==5){
              str = orderinfo["contact_mobile"];
            }else if(i==7){
              str = orderinfo["car_descrble"];
            }
           

            item["value"] = str;

        
          }

          List tempImags = this.imgs;

          for(var i =0;i<tempImags.length;i++){
             
               var url = orderinfo['car_thumb'][i];
               if(url!=''){
             tempImags[i]['url']=orderinfo['car_thumb'][i];
             List temparrStr = orderinfo['car_thumb'][i].split('attachment');
             print(temparrStr);
             //print(orderinfo['car_thumb'][i].split('attachment'));
             tempImags[i]['attachment']=temparrStr[1].substring(1,temparrStr[1].length);
             tempImags[i]['isupdate']='1';
               }
            
          }

         

          setState(() {
            formList = oldlist;
            imgs=tempImags;
            pwdData=orderinfo["car_num"];
            car_price.text=orderinfo["car_price"];
            people.text = orderinfo['contact_people'];
            mobile.text=orderinfo['contact_mobile'];
            desrible.text = orderinfo['car_descrble'];
            // orders=data["info"];
          });
          //pref.setStringList('userinfo', data["info"]);

        }
      }
    }, params: map);
  }

//提交生成检测订单
  submit() async {
    FocusScope.of(context).requestFocus(FocusNode());
    // LoadingPage loadpage = new LoadingPage(context);
    // loadpage.show();
    print(this.formList);
    Map<String, String> param = new Map();
    for (var i = 0; i < this.formList.length; i++) {
      var item = this.formList[i];
      if (item["code"] != "") {
        var code = item["code"];
        if(item["value"]==""){
          Toast.show('请填写完整的信息', context);
          return;
         // break;
        }
        param[code] = item["value"].toString();
      }
    }
     String image_Str='';
    int  isupdate=0;
    for (var i = 0; i < imgs.length; i++) {
      
      var item = imgs[i];
      print(item);
      if(item['isupdate']==1){
        isupdate++;
      }


      var tempStr="";
      if(item.containsKey('attachment')){
        tempStr = item['attachment'];
      }
      if (i == imgs.length - 1) {
        image_Str = image_Str + tempStr;
      } else
        image_Str = image_Str + tempStr + ',';
    
    }
    if(isupdate==0){
      //请上传图片
      Toast.show('请上传图片', context);
      return;
    }
    param["thumb"] = image_Str;
    param["brand_id"]=formList[1]["brand_id"];
    param["cartype_id"]=formList[2]['type_id'];
    param["car_num"]=pwdData;
    // param["price"]=formList[1]["value"].toString();
    // param["contact_people"]=formList[2]["value"].toString();
    // param["contact_mobile"]=formList[3]["value"].toString();
    // param["address"]=formList[4]["value"].toString();
    // param["car_descrble"]=formList[6]["value"].toString();
    
    SharedPreferences pref = await SharedPreferences.getInstance();

    param["oid"] = this.oid;
    print(param);

    HttpHelper.post(HttpHelper.API_BussinessSuborder, (data) async {
      //loadpage.close();
      //loadpage.close();
      if (data != null) {
        print(data);
        //Toast.show(data["msg"], context);

        if (data["code"].toString() == "1") {
         // showAlert(data["info"].toString());
          Toast.show('修改成功', context);
          //清空输入框
          // car_num.clear();
          
          // address.clear();
          // car_price.clear();
          // desrible.clear();
          // people.clear();
          // mobile.clear();
          // for(int i =0;i<formList.length;i++){
          //   formList[i]["value"]="";
          // }
          // setState(() {
          //   formList=formList;
          //   imgs=[];
          //  // img_url=[];
          // });
          
         // imgs.add('resource/images/user/upimg.png');
           
        }
      }
    }, params: param);
  }
 showAlert(id){
    showDialog<Null>(
      context: context,
      builder: (BuildContext context) {
        return new AlertDialog(
            title: Text('提示!'),
            content: new Text('您的车源已提交，若完成车况检测将会优先置顶展示'),
            actions: <Widget>[
              
              new FlatButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                    Navigator.of(context)
                          .push(new MaterialPageRoute(builder: (_) {
                        return new Papularinspects(id,2,{});
                      }));
                    //connect();
                   // Navigator.pop(context);
                  },
                  child: new Text(
                    '确定',
                    style: new TextStyle(color: Colors.black),
                  ))
            ]);
      },
    );
  }
  //输入框组件
  Widget inputWidget(item) {
    TextInputType texttype=TextInputType.text;
    if(item['text_type']==1){
    texttype = TextInputType.number;
    }else if(item['text_type']==2){
      texttype = TextInputType.text;
    }
    
    Widget content = Padding(
        padding: new EdgeInsets.fromLTRB(0, 0, 0, item["bottom"]),
        child: Container(
          color: Colors.white,
          height: 50,
          child: new Row(
            children: <Widget>[
              Expanded(
                child: new Padding(
                  padding: new EdgeInsets.fromLTRB(10, 0, 10, 0),
                  child: RichText(
                    text: TextSpan(
                        text: item["title"],
                        style: TextStyle(
                            fontSize: 15,
                            color: Color.fromRGBO(102, 102, 102, 1)),
                        children: [
                          // TextSpan(
                          //     text: '*',
                          //     style: TextStyle(fontSize: 14, color: Colors.red))
                        ]),
                  ),
                ),
                flex: 1,
              ),
               item["max_length"]>0?
              Expanded(
                
                child: new Padding(
                    padding: new EdgeInsets.fromLTRB(10, 0, 10, 0),
                    child: 
                    
                    new TextField(
                      textAlign: TextAlign.right,
                       controller: item["ctroller"],
                        maxLength: item["max_length"],maxLengthEnforced: true,
                        
                       keyboardType:texttype,
      //                  inputFormatters: <TextInputFormatter>[
      //      LengthLimitingTextInputFormatter(20)//限制长度
      //  ],

                      decoration: InputDecoration(
                        counterText:"",
                        hintText: '请输入' + item["title"],
                        border: OutlineInputBorder(
                          borderSide: BorderSide.none,
                        ),
                      ),
                      onChanged: (val) {
                        setState(() {
                          item["value"] = val;
                        });
                      },
                    )
                    )
                    ,
                flex: 2,
              )
              :Expanded(
                
                child: new Padding(
                    padding: new EdgeInsets.fromLTRB(10, 0, 10, 0),
                    child: 
                    
                    new TextField(
                      textAlign: TextAlign.right,
                       controller: item["ctroller"],
                       
                       keyboardType:texttype,
      //                  inputFormatters: <TextInputFormatter>[
      //      LengthLimitingTextInputFormatter(20)//限制长度
      //  ],

                      decoration: InputDecoration(
                        hintText: '请输入' + item["title"],
                        border: OutlineInputBorder(
                          borderSide: BorderSide.none,
                        ),
                      ),
                      onChanged: (val) {
                        setState(() {
                          item["value"] = val;
                        });
                      },
                    )
                    )
                    ,
                flex: 2,
              )
            ],
          ),
        ));
    return content;
  }

  //日期选择组件
  Widget dateSelect(item) {
    DateTime initialDate = DateTime.now();
    Widget content = Padding(
        padding: new EdgeInsets.fromLTRB(0, 0, 0, item["bottom"]),
        child: Container(
          color: Colors.white,
          height: 50,
          child: new Row(
            children: <Widget>[
              Expanded(
                child: new Padding(
                  padding: new EdgeInsets.fromLTRB(10, 0, 10, 0),
                  child: RichText(
                    text: TextSpan(
                        text: item["title"],
                        style: TextStyle(
                            fontSize: 15,
                            color: Color.fromRGBO(102, 102, 102, 1)),
                        children: [
                          // TextSpan(
                          //     text: '*',
                          //     style: TextStyle(fontSize: 14, color: Colors.red))
                        ]),
                  ),
                ),
                flex: 1,
              ),
              Expanded(
                child: Padding(
                    padding: new EdgeInsets.fromLTRB(10, 0, 20, 0),
                    child: Align(
                        alignment: Alignment.centerRight,
                        child: new GestureDetector(
                            child: new Text(item["value"]),
                            onTap: () async {
                              final DateTime dateTime = await showDatePicker(
                                context: context,
                                //定义控件打开时默认选择日期
                                initialDate: initialDate,
                                //��义控件最早可以选择的日期
                                firstDate: DateTime(2018, 1),
                                //定义控件最晚可以选择的日期
                                lastDate: DateTime(2050, 1),
                              );

                              if (dateTime != null) {
                                setState(() {
                                  String code = item["code"];
                                  item["value"] = formatDate(
                                      dateTime, [yyyy, "-", mm, "-", dd]);
                                  //formalities[code] = item["value"];
                                });
                              }
                            }))),
                flex: 2,
              )
            ],
          ),
        ));
    return content;
  }

  //车辆类型组件
  Widget cartype(item) {
    Widget content = Padding(
        padding: new EdgeInsets.fromLTRB(0, 0, 0, item["bottom"]),
        child: Container(
            color: Colors.white,
            height: 50,
            child: new GestureDetector(
              
              behavior: HitTestBehavior.opaque,
              onTap: () {
                FocusScope.of(context).requestFocus(FocusNode());
                //print('选择车型');
                if (item.containsKey("brand_id")) {
                  Navigator.of(context)
                      .push(new MaterialPageRoute(builder: (_) {
                    return new BrandSelectRoute(item);
                  }));
                } else {
                  Navigator.of(context)
                      .push(new MaterialPageRoute(builder: (_) {
                    return new CartypeSelectRoute(
                        item, formList[1]["brand_id"]);
                  }));
                }
              },
              child: new Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: <Widget>[
                  Expanded(
                    child: new Padding(
                      padding: new EdgeInsets.fromLTRB(10, 0, 10, 0),
                      child: RichText(
                        text: TextSpan(
                            text: item["title"],
                            style: TextStyle(
                                fontSize: 15,
                                color: Color.fromRGBO(102, 102, 102, 1)),
                            children: [
                              // TextSpan(
                              //     text: '*',
                              //     style: TextStyle(fontSize: 14, color: Colors.red))
                            ]),
                      ),
                    ),
                  ),
                  //  Expanded(
                  //   child:
                  new Padding(
                    padding: new EdgeInsets.fromLTRB(10, 0, 0, 0),
                    child: RichText(
                      text: TextSpan(
                          text: item["value"],
                          style: TextStyle(
                              fontSize: 15,
                              color: Color.fromRGBO(102, 102, 102, 1)),
                          children: [
                            // TextSpan(
                            //     text: '*',
                            //     style: TextStyle(fontSize: 14, color: Colors.red))
                          ]),
                    ),
                  ),

                  //),
                  // Expanded(
                  //   child:
                  Padding(
                      padding: new EdgeInsets.fromLTRB(10, 0, 20, 0),
                      child: Align(
                          alignment: Alignment.centerRight,
                          child: Image.asset(
                            'resource/images/user/detail.png',
                            height: 20,
                          ))),

                  // )
                ],
              ),
            )));
    return content;
  }

  //图片上传组件
  Widget imagUp(item) {
    Widget content = Padding(
        padding: new EdgeInsets.fromLTRB(0, 0, 0, item["bottom"]),
        child: Container(
          color: Colors.white,
          width: double.infinity,
          // height: 160,
          child: new Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              new Padding(
                padding: new EdgeInsets.fromLTRB(10, 10, 10, 0),
                child: RichText(
                  text: TextSpan(
                      text: item["title"],
                      style: TextStyle(
                          fontSize: 15,
                          color: Color.fromRGBO(102, 102, 102, 1)),
                      children: [
                        // TextSpan(
                        //     text: '*',
                        //     style: TextStyle(fontSize: 14, color: Colors.red))
                      ]),
                ),
              ),
              Padding(
                  padding: new EdgeInsets.fromLTRB(0, 0, 0, 0),
                  child: Container(
                      color: Colors.white,
                      // height: 100,
                      child: new Column(
                          mainAxisAlignment: MainAxisAlignment.start,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            new Container(child: buildCImgs())
                          ]))),

              //  Expanded(
              //   child:
            ],
          ),
        ));
    return content;
  }

  Widget textarea(item) {
    Widget content = Padding(
        padding: new EdgeInsets.fromLTRB(0, 0, 0, item["bottom"]),
        child: Container(
          color: Colors.white,
          width: double.infinity,
          // height: 160,
          child: new Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              new Padding(
                padding: new EdgeInsets.fromLTRB(10, 10, 10, 0),
                child: RichText(
                  text: TextSpan(
                      text: item["title"],
                      style: TextStyle(
                          fontSize: 15,
                          color: Color.fromRGBO(102, 102, 102, 1)),
                      children: [
                        // TextSpan(
                        //     text: '*',
                        //     style: TextStyle(fontSize: 14, color: Colors.red))
                      ]),
                ),
              ),
              Padding(
                  padding: new EdgeInsets.fromLTRB(0, 0, 0, 0),
                  child: Container(
                      color: Colors.white,
                      // height: 100,
                      child: new Column(
                          mainAxisAlignment: MainAxisAlignment.start,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            new Container(
                                child: new TextField(

                              maxLines: 10,
                              textAlign: TextAlign.left,
                        controller: item["ctroller"],
                              decoration: InputDecoration(
                                hintText: '请输入' + item["title"],
                                border: OutlineInputBorder(
                                  borderSide: BorderSide.none,
                                ),
                              ),
                              onChanged: (val) {
                                item["value"] = val;
                              },
                            ))
                          ]))),

              //  Expanded(
              //   child:
            ],
          ),
        ));
    return content;
  }

  Widget buildCImgs() {
    List<Widget> tiles = [];

    Widget content;

    List items = imgs;
    print(items);
    // print('图片数组长度'+items.isNotEmpty.toString());
    if (items.length > 0) {
      // tiles.add(new Container(
      //       padding: new EdgeInsets.fromLTRB(60, 0, 20, 0),)
      for (var i = 0; i < items.length; i++) {
        //List temp1 = items[i] as List;
        tiles.add(new Container(
          width: 120,height:140,
            padding: new EdgeInsets.fromLTRB(0, 0, 0, 0),
            child: Padding(
              padding: new EdgeInsets.fromLTRB(5, 10, 0, 10),
              child: GestureDetector(
                  onTap: () {
                    FocusScope.of(context).requestFocus(FocusNode()); //隐藏键盘
                    print('点击查看图片');
                    getImage(i);
                    // if (i == items.length - 1) {
                    //   getImage();
                    // }
                    // Navigator.of(context).push(
                    //   NinePicture(items, i),
                    //);
                  },
                  child:new Column(
                    children: <Widget>[
                    items[i]['isupdate']==0?
                  
                       Image.asset('resource/images/user/upimg.png',
                          width: 100, height: 100)
                      : CachedNetworkImage(
                        imageUrl:items[i]['url'],
                        width: 100,height: 100,
                      ),
                      //Image.network(items[i]['url'], width: 100, height: 100),
                      Center(
                        child:Text(items[i]['name'])
                      )
                      ],
                  )
            ))));
      }
    }
    content = new Wrap(
        children: tiles //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
        //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
        );
    return content;
  }
//   //选择图片
//   getimgs(type, card) async {
//     if (type == 1) {
//       var image = await ImagePicker.pickImage(source: ImageSource.gallery);

//       setState(() {
//         _image = image;
//         select_img = true;
//       });
//     } else {
//       var image = await ImagePicker.pickImage(source: ImageSource.camera);

//       setState(() {
//         _image = image;
//         select_img = true;
//       });
//     }
//     if (_image == null) return;
//     Map<String, String> map = new Map();

//     HttpHelper.upLoadImage(_image, (data) {
//       if (card == 1) {
//         setState(() {
//           card_z = data["url"];
//         });
//       } else {
//         card_f = data["url"];
//       }
//     }, params: map);
//   }

// //选择图片�����
//   Future getImage(type) async {
//     showDialog(
//         context: context,
//         builder: (BuildContext context) {
//           return new SimpleDialog(
//             title: new Text('选择'),
//             children: <Widget>[
//               new SimpleDialogOption(
//                 child: new Text('相机'),
//                 onPressed: () {
//                   Navigator.pop(context);
//                   getimgs(0, type);
//                 },
//               ),
//               new SimpleDialogOption(
//                 child: new Text('相册'),
//                 onPressed: () {
//                   Navigator.pop(context);
//                   getimgs(1, type);
//                 },
//               )
//             ],
//           );
//         });
//     // var image = await ImagePicker.pickImage(source: ImageSource.gallery);
//     // //_upLoadImage(image);//上传图片
//     // setState(() {
//     //   _image = image;
//     // });
//   }
//选择图片
  getimgs(type,index) async {
    var image;
    if (type == 1) {
      image = await ImagePicker.pickImage(source: ImageSource.gallery);
    } else {
      image = await ImagePicker.pickImage(source: ImageSource.camera);
    }
    if (image == null) return;
    // LoadingPage loadpage = new LoadingPage(context);
    // loadpage.show();
    File _files = await FlutterNativeImage.compressImage(image.path);

    Map<String, String> map = new Map();

    HttpHelper.upLoadImage(_files, (data) {
      //loadpage.close();
      print('data');
      if (data.containsKey('code')) {
        Toast.show(data['msg'], context);
      } else {
        // imgs.removeLast();
        // imgs.add(data["url"]);
        imgs[index]['isupdate']=1;
        imgs[index]['url']=data["url"];
        imgs[index]['attachment']=data["attachment"];
       // img_url[index]=(data["attachment"]);
        //imgs.add('resource/images/user/upimg.png');
        setState(() {
          imgs = imgs;
        });
      }
    }, params: map);

    // if (_image == null) return;
    // Map<String, String> map = new Map();
    // HttpHelper.upLoadImage(_image, (data) {
    //   if(data.containsKey('code')){
    //     Toast.show(data['msg'], context);
    //   }else{
    //   setState(() {
    //     avatar = data['url'];
    //   });
    //   uploadAvatar();
    //   }
    // }, params: map);
  }

//选择图片方式
  Future getImage(i) async {
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return new SimpleDialog(
            title: new Text('选择'),
            children: <Widget>[
              new SimpleDialogOption(
                child: new Text('相机'),
                onPressed: () {
                  Navigator.pop(context);
                  getimgs(0,i);
                },
              ),
              new SimpleDialogOption(
                child: new Text('相册'),
                onPressed: () {
                  Navigator.pop(context);
                  getimgs(1,i);
                },
              )
            ],
          );
        });
    // var image = await ImagePicker.pickImage(source: ImageSource.gallery);
    // //_upLoadImage(image);//上传图片
    // setState(() {
    //   _image = image;
    // });
  }

  Widget build(BuildContext context) {
    return new Scaffold(
      key: _scaffoldKey,
      appBar: new AppBar(
        title: new Text('编辑信息'),
        backgroundColor: Colors.white,
        elevation: 0,
        // backgroundColor: Color.fromRGBO(255, 204, 48, 1),
      ),
      body:  new Center(
              child: Container(
                  decoration: new BoxDecoration(
                    color: Color.fromRGBO(238, 238, 238, 1),
                  ),
                  child: Padding(
                      padding: new EdgeInsets.fromLTRB(0, 15, 0, 0),
                      child: Stack(
                        children: <Widget>[
                          Align(
                            alignment: Alignment.topCenter,
                            child: new ListView(children: <Widget>[layout()]),
                          ),
                          Align()
                        ],
                      )
                      // new ListView(
                      //   children: <Widget>[buildcontent()],
                      // )),
                      )))
         
    );
  }
}
